unit NewOrderUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls, ADODB, DBUnit, rxPlacemnt;

type
  TNewOrderForm = class(TForm)
    Label1: TLabel;
    Edit1: TEdit;
    Label2: TLabel;
    DateTimePicker1: TDateTimePicker;
    Button1: TButton;
    Button2: TButton;
    FormStorage1: TFormStorage;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  NewOrderForm: TNewOrderForm;

function CreateOrder(const aClientId: integer): integer;

implementation

{$R *.dfm}

procedure TNewOrderForm.FormCreate(Sender: TObject);
begin
  DateTimePicker1.DateTime:= Date;
end;

function CreateOrder(const aClientId: integer): integer;
var
  insertADOQuery: TADOQuery;
  showResult: integer;
begin
  CreateOrder:= 0;

  if (not Assigned(NewOrderForm)) then begin
    NewOrderForm:= TNewOrderForm.Create(nil);
  end;

  showResult:= NewOrderForm.ShowModal;
  if (showResult = mrOk) then begin
    insertADOQuery:= TADOQuery.Create(nil);
    insertADOQuery.Connection:= DBUnit.DBDataModule.DBADOConnection;
    insertADOQuery.SQL.Clear;
    insertADOQuery.SQL.Add('INSERT INTO Orders(ordernum,clientid,orderdate)');
    insertADOQuery.SQL.Add('VALUES (:aOrderNum,:aClientId,:aOrderDate)');
    insertADOQuery.Parameters.ParamByName('aOrderNum').Value:= NewOrderForm.Edit1.Text;
    insertADOQuery.Parameters.ParamByName('aClientId').Value:= aClientId;
    insertADOQuery.Parameters.ParamByName('aOrderDate').Value:= NewOrderForm.DateTimePicker1.DateTime;
    insertADOQuery.ExecSQL;
    insertADOQuery.SQL.Clear;
    insertADOQuery.SQL.Add('SELECT Orders.* FROM Orders WHERE Orders.clientid=:aClientId ORDER BY Orders.orderid desc');
    insertADOQuery.Parameters.ParamByName('aClientId').Value:= aClientId;
    insertADOQuery.Open;
    insertADOQuery.Active:= True;
    insertADOQuery.First;
    CreateOrder:= insertADOQuery.FieldByName('clientid').AsInteger;
    insertADOQuery.Close;
    insertADOQuery.Active:= False;
    FreeAndNil(insertADOQuery);
  end;
  FreeAndNil(NewOrderForm);
end;

end.
